const e = require('express');
const db = require('./db');


const Dao = {

// async checkUserLoginByUid(){

// }



 //新增用户
 //userInfo = {"openid": "string"}
 async  addUser(userInfo) {
    if (!userInfo || !userInfo.openid) {
        return {success: 0, msg: "userInfo对象不完整"};
    }
    let sql = "INSERT INTO users(openid) VALUES (?)";
    let data = [userInfo.openid];

    let result = await new Promise((resolve, reject) => {
        db.query(sql, data, (err, result) => {
            if (err) {
                resolve({success: 0, err: err, msg: "插入数据库时异常"});
            } else {
                resolve({success: 1, result: result, msg: "插入成功, 插入ID: "+ result.insertId});
            }
        });
    });

    return result;
},

//微信登录，通过openid查询用户是否存在
async  checkUserExistByOpenid(userInfo) {
    if (!userInfo || !userInfo.openid) {
        return {result: false, success: 0, msg: "userInfo对象不完整"};
    }
    let sql = `SELECT * FROM users WHERE openid = ? LIMIT 1`;
    let data = [userInfo.openid];

    try {
        const result = await db.query(sql, data);
        if (result.length > 0) {
            return {result: true, success: 1, msg: "用户已存在", uid: result[0].uid};
        } else {
            return {result: false, success: 2, msg: "用户不存在"};
        }
    } catch (error) {
        // 处理数据库查询错误或其他运行时错误
        console.error("查询数据库时出错:", error);
        return {result: false, success: 0, msg: "查询数据库时出错"};
    }
},

// 搜索列表
async hotSales(data) {
    let name = data.name;
    console.log(name);
    
    let sql = 'SELECT * FROM goods WHERE name LIKE ?';

    let result = await new Promise((resolve, reject) => {
        db.query(sql, [`%${name}%`], (err, result) => {
            if (err) {
                resolve({success: 0, err: err, msg: "查询失败"});
            } else {
                resolve({success: 1, result: result, msg: "查询成功"});
            }
        });
    });

    console.log(result);

    return result;
},

//添加地址
async AddAddress(data) {
    if (!data || !data.openid) {
        throw new Error('输入数据为空');
    }

    let openid = data.openid;
    let address = data.address;
    let name = data.name;
    let phone = data.phone;

    const updateSql = 'UPDATE users SET address = ?, name = ?, phone = ? WHERE openid = ?';
    const selectSql = 'SELECT * FROM users WHERE openid = ?';

    try {
        // 更新用户信息
        await db.query(updateSql, [address, name, phone, openid]);

        // 查询更新后的用户信息
        let userResult = await new Promise((resolve, reject) => {
            db.query(selectSql, [openid], (err, result) => {
                if (err) {
                    reject({ success: 0, msg: "查询用户信息失败！" });
                } else {
                    resolve({data: result[0]});
                }
            });
        });

        return userResult;
    } catch (error) {
        console.error('Error in AddAddress:', error);
        throw error;
    }
},

//根据jwt返回用户信息
async getUserInfoByJwt(data){
    if (!data || !data.openid) {
        throw new Error('输入数据为空');
    }

    let openid = data.openid;

    const Sql = 'SELECT * FROM users WHERE openid = ?';

    // 查询更新后的用户信息
    let result = await new Promise((resolve, reject) => {
        db.query(Sql, [openid], (err, result) => {
            if (err) {
                reject({ success: 0, msg: "查询用户信息失败！" });
            } else {
                resolve({ success: 1, msg: "查询用户信息!", data: result[0] });
            }
        });
    });
    return result;
},

//根据id获得商品信息
async getCommunityInfo(data) {
    if (!data.goodsId) {
        throw new Error('输入数据为空');
    }

    let id = data.goodsId;

    const sql = 'SELECT * FROM goods WHERE id = ?';

    try {
        const [rows] = await new Promise((resolve, reject) => {
            db.query(sql, [id], (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        if (rows.length === 0) {
            return { success: 0, msg: "查询商品信息失败！" };
        }

        return { success: 1, msg: "查询商品信息成功!", data: rows };
    } catch (error) {
        console.error('Error querying database:', error);
        return { success: 0, msg: "查询商品信息失败！" };
    }
},

//添加用户浏览记录
//添加用户浏览记录
async addBrowserLibrary(data){
    if(!data){
        throw new Error('用户数据为空');
    }

    let openid = data.openid;
    let id = data.goodsId;

    const sql = `INSERT INTO BrowserHistory (openid, goodsId) VALUES (?, ?)`;

    let result = await new Promise((resolve, reject) => {
        db.query(sql, [openid, id], (err, result) => {
            if (err) {
                resolve({ success: 0, msg: "添加用户浏览信息失败！" });
            } else {
                resolve({ success: 1, msg: "添加用户浏览信息成功!", data: result});
            }
        });
    });
    return result;
},


//根据openid获得用户浏览商品记录
async getUserBrowserHistoryByOpenId(data) {
    if (!data) {
        throw new Error('用户数据为空');
    }

    let goodsId = data;

    let sql = 'SELECT distinct * FROM goods WHERE id in (?)';

    let result = await new Promise((resolve, reject) => {
        db.query(sql, [goodsId], (err, results) => {
            if (err) {
                resolve({ success: 0, msg: "无法获得用户浏览记录！" });
            } else {
                resolve({ data: results});
            }
        });
    });
    
    return result;
},


//----------------------------------------------------------------------------------
//web端

//注册页面 用户注册
async createNewUser(userInfo){
    let sql = 'INSERT INTO admin_userinfo (account, password, email) VALUES (?, ?, ?)';
    let values = [userInfo.account, userInfo.password, userInfo.email];

    let result = await new Promise((resolve, reject) => {
            db.query(sql, values, (err, result) => {
    if (err) {
        reject({success: 0, msg: "新建用户信息成功！"});
    } else {
        resolve({success: 1, msg: "新建用户成功!"});
    }}
)
})
        return result;
},


//登录后返回这个用户的id
async userLogin(userLoginInfo){
        let sql = 'SELECT * FROM admin_userinfo WHERE account = ? AND password = ?';
        let values = [userLoginInfo.account, userLoginInfo.password];

        let result = await new Promise((resolve, reject) => {
            db.query(sql, values, (err, result) => {
                if (err) {
                    reject({success: 0, msg: "插入数据失败！"});
                } else {
                    // 使用 LAST_INSERT_ID() 获取刚刚插入的行的ID
                    let lastInsertIdSql = 'SELECT LAST_INSERT_ID() AS id';
                    db.query(lastInsertIdSql, (err, lastResult) => {
                        if (err) {
                            reject({success: 0, msg: "获取ID失败！"});
                        } else {
                            resolve({success: 1, msg: "数据插入成功!", id: lastResult[0].id});
                        }
                    });
                }
            });
        });
           return result;
},


//web端管理员更改个人信息
async updateAdminUserInfoById(admin_userinfo){
        let sql = `UPDATE admin_userinfo SET nickname = ?, self_introduction = ?, gender = ?, password = ?, email = ?, phone = ?, address = ? WHERE id = 1`;
     
        let values = [
            admin_userinfo.nickname, 
            admin_userinfo.self_introduction, 
            admin_userinfo.gender, 
            admin_userinfo.password,
            admin_userinfo.email, 
            admin_userinfo.phone, 
            admin_userinfo.address,
            admin_userinfo.id
        ];

        let result = await new Promise((resolve, reject) =>{
                db.query(sql, values, (err, result) =>{
            if(err){
                reject({success: 0, error:err, msg: "更新失败或未进行任何操作"});
            } else {
                resolve({success: 1, msg: "用户信息更新成功"});
            }
        })
    })
            return result;
},


//管理员新建活动
async  createNewActivity(newActivity){
// if(!newActivity || !newActivity.activity_name || !newActivity.keywords || !newActivity.time || !newActivity.type || !newActivity.location || !newActivity.people || !newActivity.description || !newActivity.host_department || !newActivity.co_department || !newActivity.task1_description || !newActivity.task2_description || !newActivity.task3_description || !newActivity.task4_description)
// return {success: 0, msg: "活动对象不完整"};

const sql = `INSERT INTO activity (activity_name, keywords, start_time, end_time, type, location, people, host_department, co_department, description, task1_description, task2_description, task3_description, task4_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

let values = [
    newActivity.activity_name,
    newActivity.keywords,
    newActivity.start_time,
    newActivity.end_time,
    newActivity.type,
    newActivity.location,
    newActivity.people,
    newActivity.host_department,
    newActivity.co_department,
    newActivity.description,
    newActivity.task1_description,
    newActivity.task2_description,
    newActivity.task3_description,
    newActivity.task4_description
]

    let result = await new Promise((resolve, reject) => {
        db.query(sql, values, (err, result) =>{
    //数据库操作后返回的属性, 1和0
    if (err){
        if (err.code === 'ER_DUP_ENTRY'){
            reject({success: 0, error: err, msg: "活动已存在!"});
        }else{
            reject({success: 0, msg: "新建活动失败!"});
        }
     }else{
        resolve({success: 1, msg: "新建活动成功!"});
    }
    });
});
           return result;
},

//查看所有活动 
async  getAllActivities(){
        let sql = `SELECT * FROM activity`;
        let result = await new Promise((resolve, reject) =>{
            db.query(sql, (err, result)=>{
                if(err){
                    reject({success: 0, error: err, msg: "更新数据库记录时异常"});
                }else{
                    resolve({success: 1, data: result, msg: "查询成功"});
                }
         });
    })
             return result;
},

//从活动列表点击某活动，查看详情
//根据活动名
async  activityDetails(activityName){
        let sql = `SELECT * FROM activity WHERE activity_name = ?`;

        let result = await new Promise((resolve, reject) => {
             db.query(sql, activityName, (err, result) => {
                if(err){
                   reject({success: 0, error: err, msg: "查看活动失败"}); 
                }else{
                    resolve({success: 1, msg: "查看活动成功", data: result});
                }
        });
});
        return result;
},

//添加商品
async addGoods(newGoods){
        let sql = `INSERT INTO goods (name, price, type, description, image, origin, introduction, stock, market_price, cost_price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
        let values = [newGoods.name, newGoods.price, newGoods.type, newGoods.description, newGoods.image, newGoods.origin, newGoods.introduction, newGoods.stock, newGoods.market_price, newGoods.cost_price];

        let result = await new Promise((resolve, reject) => {
           db.query(sql, values, (err, result) => {
                if(err){
            reject({success: 0, error:err, msg: "添加商品失败!"});
                }else{
            resolve({success: 1, msg: "添加商品成功!"});
            }
    });
});
    return result;
}






};


module.exports = Dao;


// let sql = "INSERT INTO Users(openid) VALUES (?)";
//         let data = [userInfo.openid];
    
//         let result = await new Promise((resolve, reject) => {
//             db.query(sql, data, (err, result) => {
//                 if (err) {
//                     reject({success: 0, err: err, msg: "插入数据库时异常"});
//                 } else {
//                     resolve({success: 1, result: result, msg: "插入成功, 插入ID: "+ result.insertId});
//                 }
//             });
//         });




//查询用户是否存在
//userInfo = {"openid": "string"}
